<template>
  <div class="weaning-list-container">
    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <div class="search-form">
        <div class="form-row">
          <div class="form-item">
            <label>断奶日期</label>
            <div class="date-range">
              <el-date-picker v-model="page.StartWeaningTime" type="date" placeholder="开始日期" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" size="default" />
              <span class="date-separator">至</span>
              <el-date-picker v-model="page.EndWeaningTime" type="date" placeholder="结束日期" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" size="default" />
            </div>
          </div>
          <div class="form-item">
            <label>种母耳号</label>
            <el-input v-model="page.WeaningSnowId" placeholder="请输入种母耳号" clearable />
          </div>
          <div class="form-item">
            <label>转入栋舍</label>
            <el-select v-model="page.WeaningTransferhouse" placeholder="请选择转入栋舍" clearable class="select-input">
              <el-option label="大羊舍" value="大羊舍" />
              <el-option label="配种舍" value="配种舍" />
              <el-option label="采购羊栋舍" value="采购羊栋舍" />
            </el-select>
          </div>
          <div class="form-item">
            <label>负责人</label>
            <el-select v-model="page.ResponsibleFor" placeholder="请选择">
              <el-option label="海绵宝宝" value="海绵宝宝" />
              <el-option label="派大星" value="派大星" />
              <el-option label="蟹老板" value="蟹老板" />
            </el-select>
          </div>
        </div>
        <div class="form-actions">
          <el-button type="primary" @click="loadData" class="search-btn">
            查询
          </el-button>
          <el-button @click="handleReset" class="reset-btn">
            重置
          </el-button>
          <el-button @click="toggleCollapse" class="collapse-btn">
            收起
            <el-icon class="collapse-icon">
              <ArrowUp />
            </el-icon>
          </el-button>
        </div>
      </div>
    </div>

    <!-- 操作工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <el-button type="primary" @click="handleAdd" class="add-btn">
          <el-icon>
            <Plus />
          </el-icon>
          新增
        </el-button>
        <el-button @click="handleBatchDelete" :disabled="selectedRows.length === 0" class="delete-btn">
          <el-icon>
            <Delete />
          </el-icon>
          删除
        </el-button>
        <el-button @click="handleBatchReview" :disabled="selectedRows.length === 0" class="review-btn">
          <el-icon>
            <User />
          </el-icon>
          审核
        </el-button>
        <div class="selection-info">
          <el-icon class="info-icon">
            <InfoFilled />
          </el-icon>
          已选择 {{ selectedRows.length }} 项
        </div>
      </div>
      <div class="toolbar-right">
        <el-icon class="toolbar-icon">
          <Refresh />
        </el-icon>
        <el-icon class="toolbar-icon">
          <Setting />
        </el-icon>
        <el-icon class="toolbar-icon">
          <Filter />
        </el-icon>
        <el-icon class="toolbar-icon">
          <MoreFilled />
        </el-icon>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table :data="tableData" @selection-change="handleSelectionChange" class="data-table" stripe border>
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="WeaningTime" label="断奶日期" width="120" sortable>
          <template #default="{ row }">
            {{ formatDate(row.weaningDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="weaningSnowId" label="耳号" width="120" />
        <el-table-column prop="weaningDayNum" label="哺乳天数" width="100" />
        <el-table-column prop="weaningMomweight" label="种母重量(公斤)" width="140" />
        <el-table-column prop="weaningQuantity" label="断奶只数" width="100" />
        <el-table-column prop="weaningWeight" label="断奶总窝重(公斤)" width="160" />
        <el-table-column prop="weaningPoultryhome" label="当前栋舍" width="120" />
        <el-table-column prop="weaningField" label="当前栏位" width="120" />
        <el-table-column prop="weaningTransferhouse" label="转入栋舍" width="120" />
        <el-table-column prop="weaningTransfer" label="转入栏位" width="120" />
        <el-table-column prop="responsibleFor" label="负责人" width="100" />
        <el-table-column prop="documentNumber" label="单据号" width="1s40" />
        <el-table-column prop="weaningDesc" label="断奶原因" width="120" />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button link type="danger" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <div class="pagination-info">
        <!-- <span>当前为第{{ pagination.currentPage }}页共{{ pagination.totalPages }}页{{ pagination.total }}条数据</span> -->
        <el-pagination v-model:current-page="page.pageIndex" v-model:page-size="page.pageSize" :page-sizes="[1, 2, 3, 4]"
          :size="page.pageSize" :background="page.totalCount" layout="total, sizes, prev, pager, next, jumper"
          :total="page.totalCount" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowUp,
  Plus,
  Delete,
  User,
  InfoFilled,
  Refresh,
  Setting,
  Filter,
  MoreFilled
} from '@element-plus/icons-vue'
import { Reads, Writes } from '@/Utils/axiosHelper';
import { useRouter } from 'vue-router';

const router = useRouter()
// 搜索表单
const searchForm = reactive({
  weaningDateRange: [],
  earTag: '',
  transferBuilding: '',
  responsiblePerson: ''
})

// 表格数据
const tableData = ref<any[]>([])
const selectedRows = ref<any[]>([])

// 分页
const page = reactive({
  pageIndex: 1,
  pageSize: 5,
  totalCount: 0,
  totalPage: 0,
  StartWeaningTime: "",
  EndWeaningTime: "",
  WeaningSnowId: "",
  WeaningTransferhouse: "",
  ResponsibleFor: ""
})
// 初始化
onMounted(() => {
  loadData()
})
// 加载数据
const loadData = async () => {
  Reads.get("Management/GetWeanings", {
    params: page
  })
    .then(res => {
      tableData.value = res.data.data.data

      page.totalCount = res.data.data.totalCount
      page.totalPage = res.data.data.totalPage
    })
}
watch(page, () => {
  loadData()
}, { deep: true })
// 搜索
const handleSearch = () => {
  loadData()
}

// 重置
const handleReset = () => {
  Object.assign(page, {
    StartWeaningTime: "",
    EndWeaningTime: "",
    WeaningSnowId: "",
    WeaningTransferhouse: "",
    ResponsibleFor: ""
  })
  loadData()
}

// 收起/展开
const toggleCollapse = () => {
  // 实现收起/展开逻辑
  console.log('Toggle collapse')
}

// 新增
const handleAdd = () => {
  // 跳转到新增页面或打开弹窗
  router.push('EweWeaning')
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的记录')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 条记录吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const ids = selectedRows.value.map(row => row.id)
    Writes.delete('/api/weaning-records/batch', { data: { ids } })

    ElMessage.success('删除成功')
    selectedRows.value = []
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error('Batch delete error:', error)
    }
  }
}

// 批量审核
const handleBatchReview = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要审核的记录')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要审核选中的 ${selectedRows.value.length} 条记录吗？`,
      '确认审核',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const ids = selectedRows.value.map(row => row.id)
    Writes.put('/api/weaning-records/batch-review', { ids })

    ElMessage.success('审核成功')
    selectedRows.value = []
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('审核失败')
      console.error('Batch review error:', error)
    }
  }
}

// 编辑
const handleEdit = (row: any) => {
  console.log('Edit weaning record:', row)
}

// 删除
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条记录吗？',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    Writes.delete(`/api/weaning-records/${row.id}`)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error('Delete error:', error)
    }
  }
}

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}
// 格式化日期
const formatDate = (date: string) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString('zh-CN')
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 组件挂载时加载数据
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.weaning-list-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 搜索区域 */
.search-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-item label {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.form-item .el-input,
.form-item .el-select,
.form-item .el-date-picker {
  width: 100%;
}

.form-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

.search-btn {
  background-color: #dc2626;
  border-color: #dc2626;
  color: white;
  padding: 8px 20px;
}

.search-btn:hover {
  background-color: #b91c1c;
  border-color: #b91c1c;
}

.reset-btn,
.collapse-btn {
  background-color: white;
  border-color: #d1d5db;
  color: #374151;
  padding: 8px 20px;
}

.collapse-icon {
  margin-left: 4px;
}

/* 工具栏 */
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 16px 20px;
  border-radius: 8px;
  margin-bottom: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.add-btn {
  background-color: #dc2626;
  border-color: #dc2626;
  color: white;
  padding: 8px 16px;
}

.add-btn:hover {
  background-color: #b91c1c;
  border-color: #b91c1c;
}

.delete-btn,
.review-btn {
  background-color: #f3f4f6;
  border-color: #d1d5db;
  color: #374151;
  padding: 8px 16px;
}

.delete-btn:hover,
.review-btn:hover {
  background-color: #e5e7eb;
}

.selection-info {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #6b7280;
  font-size: 14px;
}

.info-icon {
  color: #dc2626;
}

.toolbar-right {
  display: flex;
  gap: 16px;
}

.toolbar-icon {
  color: #6b7280;
  cursor: pointer;
  font-size: 18px;
}

.toolbar-icon:hover {
  color: #374151;
}

/* 表格 */
.table-container {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 16px;
}

.data-table {
  width: 100%;
}

:deep(.el-table__header) {
  background-color: #f9fafb;
}

:deep(.el-table__header th) {
  background-color: #f9fafb;
  color: #374151;
  font-weight: 600;
  border-bottom: 2px solid #dc2626;
}

:deep(.el-table__row:hover) {
  background-color: #f8fafc;
}

:deep(.el-table__empty-text) {
  color: #9ca3af;
  font-size: 16px;
}

/* 分页 */
.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 16px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-size-label {
  color: #6b7280;
  font-size: 14px;
}

.page-size-select {
  width: 80px;
}

:deep(.page-size-select .el-input__inner) {
  text-align: center;
}

.pagination-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.pagination-info {
  color: #6b7280;
  font-size: 14px;
}

:deep(.pagination .el-pager li.is-active) {
  background-color: #dc2626;
  color: white;
}

:deep(.pagination .el-pagination__prev:hover),
:deep(.pagination .el-pagination__next:hover) {
  color: #dc2626;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .form-row {
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  }
}

@media (max-width: 768px) {
  .weaning-list-container {
    padding: 12px;
  }

  .form-row {
    grid-template-columns: 1fr;
  }

  .toolbar {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .toolbar-left {
    justify-content: center;
  }

  .toolbar-right {
    justify-content: center;
  }

  .pagination-container {
    flex-direction: column;
    gap: 12px;
  }

  .pagination-right {
    flex-direction: column;
    gap: 8px;
  }
}

@media (max-width: 480px) {
  .toolbar-left {
    flex-wrap: wrap;
    justify-content: center;
  }

  .form-actions {
    flex-direction: column;
  }

  .search-btn,
  .reset-btn,
  .collapse-btn {
    width: 100%;
  }
}
</style>
